using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WPCoco.Tasks
{
    public class Spawn : Task, IContainer<Task>
    {
        public Spawn(params Task[] tasks)
        {
            innerTasks = tasks;
            actives = new bool[innerTasks.Length];
        }

        Task[] innerTasks;
        bool[] actives;
        int activeCount;

        public override void Initialize()
        {
            base.Initialize();
            for (int i = 0; i < innerTasks.Length; i++)
            {
                innerTasks[i].Initialize();
                actives[i] = true;
            }
            activeCount = innerTasks.Length;
        }

        public override void Update(float time)
        {
            if (HasEnded()) return;
            for (int i = 0; i < innerTasks.Length; i++)
            {
                if (actives[i]) 
                {
                    innerTasks[i].Update(time);
                    if (innerTasks[i].HasEnded())
                    {
                        innerTasks[i].Finish();
                        actives[i] = false;
                        activeCount--;
                    }
                }
            }   
        }

        public override bool HasEnded()
        {
            return activeCount == 0;    
        }

        public override void Finish()
        {
            
        }

        public override Task Clone()
        {
            Task[] innerCloned = new Task[innerTasks.Length];
            for (int i = 0; i < innerTasks.Length; i++)
                innerCloned[i] = innerTasks[i].Clone();
            Spawn task = new Spawn(innerCloned);
            return task;
        }

        public override Task Reverse()
        {
            Task[] innerCloned = new Task[innerTasks.Length];
            for (int i = 0; i < innerTasks.Length; i++)
                innerCloned[i] = innerTasks[i].Reverse();
            Spawn task = new Spawn(innerCloned);
            return task; 
        }

        #region IContainer<Task> Members

        public IEnumerable<Task> GetContainerEnumerator()
        {
            for (int i = 0; i < innerTasks.Length; i++)
                yield return innerTasks[i];
            yield break;
        }

        #endregion
    }
}
